package leetcode.tree;

/**
 * @author wangmaolin1
 * @date 2022/1/3 下午5:09
 */

public class _463岛屿的周长 {

    public int islandPerimeter(int[][] grid) {
        int length = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == 1) {
                    length += dfs(grid, i, j);
                }
            }
        }
        return length;
    }

    private int dfs(int[][] grid, int i, int j) {
        if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == 0 || grid[i][j] == 2) {
            return 0;
        }
        int len = 0;
        if (grid[i][j] == 1) {
            len += getLength(grid, i, j);
            grid[i][j] = 2;
        }
        len += dfs(grid, i - 1, j);
        len += dfs(grid, i + 1, j);
        len += dfs(grid, i, j - 1);
        len += dfs(grid, i, j + 1);

        return len;
    }

    private int getLength(int[][] grid, int i, int j) {
        int total = 0;

        if (i == 0 || grid[i - 1][j] == 0) {
            //上边界或上面是水
            total++;
        }
        if (i == grid.length - 1 || grid[i + 1][j] == 0) {
            //下边界或下边是水
            total++;
        }
        if (j == 0 || grid[i][j - 1] == 0) {
            //左边界或左边为水
            total++;
        }
        if (j == grid[i].length - 1 || grid[i][j + 1] == 0) {
            //右边界或右边是水
            total++;
        }
        System.out.println(i + "," + j + ":" + total);
        return total;
    }

    /*
            0 1 0 0
            1 1 1 0
            0 1 0 0
            1 1 0 0
     */
    public static void main(String[] args) {
        int[][] grid = new int[4][4];
        grid[0] = new int[]{0, 1, 0, 0};
        grid[1] = new int[]{1, 1, 1, 0};
        grid[2] = new int[]{0, 1, 0, 0};
        grid[3] = new int[]{1, 1, 0, 0};
        int i = new _463岛屿的周长().islandPerimeter(grid);
        System.out.println(i);
    }
}
